const state = {
	mid: new Date().getTime(),
	mConter: 0,	
	tid: null,
	port : null,
	portName: 'content:' + new Date().getTime(),
	connected: false,
	isReconnect: false,	
	serviceRefs: null
};

let eventDriver = null;

const genOneSeqId = () => {
	state.mConter = state.mConter + 1;
	return state.mid + state.mConter;

};

const register = () => {
	state.port = chrome.runtime.connect(null, {name: state.portName});
	state.port.onMessage.addListener(function(msg){
		handlePortMsg(msg);
	
	});
	
	state.port.onDisconnect.addListener(function(){
		console.log('back connection lost');
		self.port = null;
		self.connected = false;
		self.isReconnect = true;
		register();

	});

	state.connected = true;
	if(!state.isReconnect){
		console.log('backend connection established....');
		sendMessage({type: 'event', data: {name: 'ping'}}, state.port);
	}

};

const startKeeper = (refs) => {
	register();
	state.serviceRefs = refs;
	eventDriver.emit('dom-event', {name: 'build-nodes-map'});

};

const handlePortMsg = (msgInfo) => {
	let type = msgInfo.type;
	let name = null == msgInfo.data ? '' : msgInfo.data.name;
	let data = msgInfo.data;
	if('event' == type && 'pong' == name){
		state.tabId = data.data;
		return;
	}
	if('event' == type && 'actionClick' === name){
		eventDriver.emit('app-action-event', msgInfo);
		return;
	}

	console.log(msgInfo);

};

const sendMessage = (msgInfo) => {
	msgInfo.from = 'content';
	msgInfo.sender = state.portName;
	msgInfo.sid = 'content:' + genOneSeqId();
	msgInfo.tid = state.tabId;
	if(!state.connected){
		return;
	}
	state.port.postMessage(msgInfo);

};

const initSetup = (driver) => {
	eventDriver = driver;
	eventDriver.on('startup', (refs) => startKeeper(refs));
	eventDriver.on('msg-forward-event', (msgInfo) => sendMessage(msgInfo));

};

export default function(driver){
	initSetup(driver);
	return {
		sendMessage
	};

};